import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-08-06
 * Time: 19:02
 */
public class JDBC_Demo1 {
    public static void main(String[] args) throws SQLException {
        //假定数据库中有一个student表(id, name),往里面插入数据。

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号");
        int id = scanner.nextInt();
        System.out.println("请输入名字");
        String name = scanner.next();

        //1.创建“数据源”
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java1?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("111111");

/*      MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUrl("");*/

        //2. 和数据库服务器建立联系
        Connection connection = dataSource.getConnection();

        // 3. 构造 SQL 语句
        String sql = "insert into student values (?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        statement.setString(2,name);

        // 4. 执行 SQL 语句, 返回值就是这次操作影响几行
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        //释放必要资源，关闭连接。
        //后创建的先关闭，先创建的后关闭
        statement.close();
        connection.close();

    }
}
